package com.note.app.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.note.common.domain.DocCollection;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
 * 集合Mapper接口
 */
@Mapper
public interface CollectionMapper extends BaseMapper<DocCollection> {

    /**
     * 分页查询用户集合列表
     * 
     * @param page 分页参数
     * @param userId 用户ID
     * @param parentId 父级集合ID
     * @return 分页结果
     */
    @Select("<script>" +
            "SELECT * FROM collection WHERE user_id = #{userId} AND deleted = 0 " +
            "<if test='parentId != null'> AND parent_id = #{parentId} </if>" +
            "<if test='parentId == null'> AND (parent_id IS NULL OR parent_id = 0) </if>" +
            "ORDER BY created_at DESC" +
            "</script>")
    IPage<DocCollection> selectPageByUserId(Page<DocCollection> page, 
                                         @Param("userId") Long userId, 
                                         @Param("parentId") Long parentId);
    
    /**
     * 查询用户下的所有集合（用于构建树）
     * 
     * @param userId 用户ID
     * @return 集合列表
     */
    @Select("SELECT * FROM collection WHERE user_id = #{userId} AND deleted = 0 ORDER BY created_at DESC")
    List<DocCollection> selectAllByUserId(@Param("userId") Long userId);
    
    /**
     * 查询指定父级下的子集合
     * 
     * @param userId 用户ID
     * @param parentId 父级集合ID
     * @return 子集合列表
     */
    @Select("<script>" +
            "SELECT * FROM collection WHERE user_id = #{userId} AND deleted = 0 " +
            "<if test='parentId != null'> AND parent_id = #{parentId} </if>" +
            "<if test='parentId == null'> AND (parent_id IS NULL OR parent_id = 0) </if>" +
            "ORDER BY created_at DESC" +
            "</script>")
    List<DocCollection> selectChildrenByParentId(@Param("userId") Long userId, @Param("parentId") Long parentId);
} 